package com.stephen.redisdemo.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author: stephen
 * @create: 2020-03-01 14:41
 * @description: 三种线程池的使用
 * 底层都是 ThreadPoolExecutor
 */
public class ThreadPoolDemo {

    public static void main(String[] args) {
        // 一个池中线程数量固定
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        // 一个池中只有一个线程
        ExecutorService threadPool1 = Executors.newSingleThreadExecutor();
        // 一个池中有N个线程,随着处理业务自动变化,可能只有一个,也可能有多个
        ExecutorService threadPool2 = Executors.newCachedThreadPool();

        try {
            for (int i = 0; i < 10; i++) {
                threadPool2.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "\t 处理业务");
                });
                TimeUnit.MILLISECONDS.sleep(200);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭线程池
            threadPool.shutdown();
        }

    }

}
